package com.xiaofengstu.mcams.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.xiaofengstu.mcams.constant.SysConstants;
import com.xiaofengstu.mcams.exception.BizException;
import com.xiaofengstu.mcams.web.entity.TUser;
import com.xiaofengstu.mcams.web.service.TUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Optional;


/**
 * @Author FengZeng
 * @Date 2022-05-10 23:06
 * @Description TODO
 */
@Component
@RequiredArgsConstructor
public class JwtUtils {

  private final TUserService userService;
  private static String secretKey;

  @Value("${jwt.secretKey}")
  public void setSecret(String secretKey) {
    JwtUtils.secretKey = secretKey;
  }

  public String getToken(Integer userId) {
    return JWT.create()
        .withClaim(SysConstants.USER_ID, userId)
        .sign(Algorithm.HMAC256(secretKey));
  }

  public TUser getCurrentUser(String token) {
    Integer userId = JWT.decode(token).getClaim(SysConstants.USER_ID).asInt();
    Optional<TUser> u = Optional.ofNullable(userService.getById(userId));
    if (!u.isPresent()) {
      throw new BizException();
    }
    return u.get();

  }



}
